package com.joinway.framework.extension.cipher;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public final class AES {

	final private static String ALGORITHM = "AES";

	/**
	 * 
	 * @param text
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String text, String key) throws Exception {
		return Base64.encodeBase64String(cipher(text.getBytes(), key, Cipher.ENCRYPT_MODE)).replace("\r\n", "");
	}

	public static String decrypt(String text, String key) throws Exception {
		return new String(cipher(Base64.decodeBase64(text.getBytes()), key, Cipher.DECRYPT_MODE));
	}

	static byte[] cipher(byte[] data, String key, int mode) throws Exception {
		if (key == null || key.length() < 16) {
			throw new Exception("key must greater than 128 bits");
		}

		Key aesKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(mode, aesKey);

		return cipher.doFinal(data);
	}

	private AES() {}
}